<?php


namespace app\util;

use Swoole\Http\Request;
use Swoole\Http\Response;

class CallFun
{
    public function call(Request $request, Response $response)
    {
        list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
        $controller = ucfirst($controller);
        $controller = "app\\module\\controller\\" . $controller;

        $response->header('Content-Type', 'text/json; charset=utf-8');

        $middle = include(__DIR__ . '/../config/middleware.php');
        foreach ($middle as $class => $rule) {
            if (in_array($controller, $rule['black'])) {
                $response = (new $class)->run($request, $response);
                if ($response instanceof Response && !$response->isWritable()) {
                    return;
                }
            }
        }
        $args = [$request->post, (new Token())->decode($request->header['token'] ?? 'a.a.a')];
        $data = (new $controller)->$action(...$args);
        $response->end(json_encode(ApiReturn::success($data)));
    }
}